package com.gomoku.backend.service.impl.user;

import com.gomoku.backend.pojo.User;
import com.gomoku.backend.service.impl.utils.UserDetailsImpl;
import com.gomoku.backend.service.user.LoginService;
import com.gomoku.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;


    @Override
    public Map<String,String> gettoken(String username,String password){

        //这个是登录的时候实例化一遍，直接用用户名和密码生成的，以后都是什么 SecurityContextHolder上下文里面获取
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,password);

        Authentication authenticate = authenticationManager.authenticate(token);//如果失败的话会自动报异常
        UserDetailsImpl userDetails = (UserDetailsImpl) authenticate.getPrincipal();
        User loginUser = userDetails.getUser();//这个应该是注解实现的，或者继承的
        String jwt = JwtUtil.createJWT(loginUser.getId().toString()); //jwt是由 id和密钥生成

        Map<String,String> map = new HashMap<>();
        map.put("error_message","success");
        map.put("token",jwt);
        return map;
    }
}
